﻿using Sobiens.SPCamlStudio.Common;
using Sobiens.SPCamlStudio.Entities;
using Sobiens.SPCamlStudio.Entities.Interfaces;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Sobiens.SPCamlStudio.UI.Controls
{
    /// <summary>
    /// Interaction logic for ResultPane.xaml
    /// </summary>
    public partial class ResultPane : UserControl
    {
        private ISiteSetting siteSetting;
        private CamlFilters filters;
        private List<CamlFieldRef> viewFields;
        private CamlQueryOptions queryOptions;
        private List<CamlOrderBy> orderBys;

        public ResultPane()
        {
            InitializeComponent();
        }

        public void PopulateResults(ISiteSetting siteSetting, string webUrl, string listName, CamlFilters _filters, List<CamlFieldRef> _viewFields, List<CamlOrderBy> _orderBys, CamlQueryOptions _queryOptions)
        {
            filters = _filters;
            viewFields = _viewFields;
            orderBys= _orderBys;
            queryOptions = _queryOptions;
            string listItemCollectionPositionNext;
            int itemCount;
            List<IItem> items = ApplicationContext.Current.GetListItems(siteSetting, orderBys, filters, viewFields, queryOptions, webUrl, listName, out listItemCollectionPositionNext, out itemCount);
            DataTable dataTable = new DataTable();
            ResultGrid.Columns.Clear();
            foreach (CamlFieldRef fieldRef in _viewFields)
            {
                DataGridTextColumn column = new DataGridTextColumn();
                column.IsReadOnly = true;
                column.Binding = new Binding(fieldRef.Name);
                column.Header = fieldRef.DisplayName;
                ResultGrid.Columns.Add(column);
                dataTable.Columns.Add(fieldRef.Name);
            }
            foreach (IItem item in items)
            {
                DataRow row = dataTable.NewRow();
                foreach (CamlFieldRef fieldRef in _viewFields)
                {
                    string key = "ows_" + fieldRef.Name;
                    if(item.Properties.ContainsKey(key) == true)
                        row[fieldRef.Name] = item.Properties["ows_" + fieldRef.Name];
                }
                dataTable.Rows.Add(row);
            }

            ResultGrid.ItemsSource = dataTable.AsDataView();
        }
    }
}
